import React, { Children, forwardRef, useEffect, useImperativeHandle, useState } from 'react';

import {
  Button,
  DatePicker,
  Form,
  Input,
  Modal,
  Radio,
  Tag,
  Select,
  InputNumber,
  Divider,
  Row,
  Col,
  Checkbox,
  TreeSelect
} from 'antd';
import { modalLayoutLg, modalLayoutSm } from '@/config/layout';
import type { CheckboxChangeEvent } from 'antd/es/checkbox';
import type { CheckboxValueType } from 'antd/es/checkbox/Group';
import { request } from 'umi';
import moment from 'moment';
const { Option } = Select;
const CheckboxGroup = Checkbox.Group;
const ProductModal = (props: any, refs: any) => {
  const [form] = Form.useForm();
  // const [fileList,setfileList] = useState([]);
  const [measureClassData, setmeasureClassData] = useState([]);
  const { setFieldsValue, resetFields } = form;
  const [code, setCode] = useState('');
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [orglist, setorglist] = useState([]);
  const [deptList, setDeptList] = useState([]);
  const [companyList, setCompanyList] = useState([]);
  const [accessibleUsersList, setAccessibleUsersList] = useState([]);
  const [roleList, setRoleList] = useState([]);
  //人员身份列表
  const [userRoleTypeListEnum, setUserRoleTypeListEnum] = useState([]);
  //人员类型列表
  const [userTypeListEnum, setUserTypeListEnum] = useState([]);
  //人员档案列表
  const [personListEnum, setPersonListEnum] = useState([]);

  // 公司选中集合
  const [checkedCompanyList, setCheckedCompanyList] = useState<CheckboxValueType[]>([]);
  const checkCompanyAll = companyList.length > 0 && companyList.length === checkedCompanyList.length;

  //角色选中集合
  const [checkedRoleList, setCheckedRoleList] = useState<CheckboxValueType[]>([]);
  const checkRoleAll = roleList.length > 0 && roleList.length === checkedRoleList.length;
  // 人员选中集合
  const [checkedUserList, setCheckedUserList] = useState<CheckboxValueType[]>([]);
  const checkUserAll = accessibleUsersList.length > 0 && accessibleUsersList.length === checkedUserList.length;
  //公司全选
  const indeterminateCompany = checkedCompanyList.length > 0 && checkedCompanyList.length < companyList.length;
  //角色全选
  const indeterminateRole = checkedRoleList.length > 0 && checkedRoleList.length < roleList.length;
  //人员全选
  const indeterminateUser = checkedUserList.length > 0 && checkedUserList.length < accessibleUsersList.length;
  //查询用户归属角色类型列表
  const getUserRoleTypeList = () => {
    request('/sys/dict/getDictListByType', {
      method: 'POST',
      data: { type: 'user_role_type' },
    }).then((res) => {
      let list = res?.data || [];
      list.map((e, i) => {
        list[i]['name'] = e['label'];
        list[i]['key'] = e['value'];
      });
      setUserRoleTypeListEnum(list);
    });
  };

  //用户类型
  const getUserTypeList = () => {
    request('/sys/dict/getDictListByType', {
      method: 'POST',
      data: { type: 'user_type' },
    }).then((res) => {
      let list = res?.data || [];
      list.map((e, i) => {
        list[i]['name'] = e['label'];
        list[i]['key'] = e['value'];
      });
      setUserTypeListEnum(list);
    });
  };

  //查询用户归属角色类型列表
  const getPersonList = () => {
    request('/sys/dictUtils/findPersonList', {
      method: 'POST',
      data: {},
    }).then((res) => {
      let list = res?.data || [];
      list.map((e, i) => {
        list[i]['name'] = e['personName'];
        list[i]['key'] = e['id'];
      });
      setPersonListEnum(list);
    });
  };


  //公司选择触发
  const onCompanyChange = (list: CheckboxValueType[]) => {
    setCheckedCompanyList(list);
  };

  const onCheckAllCompanyChange = (e: CheckboxChangeEvent) => {
    let arr = companyList.map((item) => item.id);
    setCheckedCompanyList(e.target.checked ? arr : []);
  };

  //角色选择触发
  const onRoleChange = (list: CheckboxValueType[]) => {
    setCheckedRoleList(list);
  };

  const onCheckAllRoleChange = (e: CheckboxChangeEvent) => {
    let arr = roleList.map((item) => item.id);
    setCheckedRoleList(e.target.checked ? arr : []);
  };



  //人员选择触发
  const onUserChange = (list: CheckboxValueType[]) => {
    setCheckedUserList(list);
  };

  const onCheckAllUserChange = (e: CheckboxChangeEvent) => {
    let arr = accessibleUsersList.map((item) => item.id);
    setCheckedUserList(e.target.checked ? arr : []);
  };
  // const [checkedCompany, setCheckedCompany] = useState([]);
  //获取公司集合
  const getCompanyList = () => {
    request('/sys/dictUtils/findAffiliatedCompanyList', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      data: {},
    }).then((res) => {
      let list = res?.data || [];
      list.map((e, i) => {
        list[i]['label'] = e['companyName'];
        list[i]['value'] = e['id'];
      });
      setCompanyList(list);
    });
    //
  };
  //获取公司集合
  const getRoleList = () => {
    request('/sys/dictUtils/findRoleList', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      data: {},
    }).then((res) => {
      let list = res?.data || [];
      list.map((e, i) => {
        list[i]['label'] = e['name'];
        list[i]['value'] = e['id'];
      });
      setRoleList(list);
    });
    //
  };



  //获取已经选中的人员
  const getAccessibleUsersList = () => {
    request('/sys/dictUtils/findAccessibleUsersList', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      data: {},
    }).then((res) => {
      let list = res?.data || [];
      list.map((e, i) => {
        list[i]['label'] = e['accessibleUserName'];
        list[i]['value'] = e['accessibleUsersId'];
      });
      setAccessibleUsersList(list);
    });
    //
  };
  //获取被选中的公司
  const getCheckedCompanyList = (userId) => {
    request('/sys/user-affiliated-company/allList', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      data: { userId: userId },
    }).then((res) => {
      let list = [];
      let data = res?.data || [];
      data.map((e, i) => {
        list.push(e['affiliatedComapnyId']);
      });
      setCheckedCompany(list);
    });
    //
  };

  //获取被选中的角色
  const getCheckedRoleList = (userId) => {
    request('/sys/dictUtils/findRoleListByUserId', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      data: { userId: userId },
    }).then((res) => {
      let list = [];
      let data = res?.data || [];
      data.map((e, i) => {
        list.push(e['roleId']);
      });
      setCheckedRole(list);
    });
    //
  };


  const getOrgList = () => {
    request('/sys/account/findOfficeTreeList', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      data: {},
    }).then((res) => {
      setorglist(res?.data || []);
    });
    //
  };
  //部门下拉框
  const getDeptList = () => {
    request('/sys/department/list', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      data: { "current": 1, "pageSize": 100000, "pageNo": 1 },
    }).then((res) => {
      setDeptList(res?.data?.data || []);
    });
    //
  };
  useEffect(() => {
    getOrgList();
    getDeptList();

    getCompanyList();
    getRoleList();
    getUserRoleTypeList();
    getUserTypeList();
    getPersonList();
    getAccessibleUsersList();
  }, []);
  //显示弹窗
  const showModal = () => {
    setIsModalVisible(true);
  };

  //取消
  const handleCancel = () => {
    setIsModalVisible(false);
    setCode('');
    resetFields();
    setCheckedCompanyList([]);
    setCheckedRoleList([]);
    setCheckedUserList([]);
    props.callback && props.callback();
  };

  //确定
  const handleOk = () => {
    form
      .validateFields()
      .then((vals) => {
        let Obj = form.getFieldsValue();
        Obj = {
          ...Obj,
          ...{
            "affiliatedCompanyIds": checkedCompanyList,
            "roleIds": checkedRoleList,
            "accessibleUsersIds": checkedUserList
          }
        };

        const url = code ? '/sys/account/save' : '/sys/account/save';
        if (code) {
          Obj.id = code;
        } else {
        }

        request(url, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          data: Obj,
        }).then(async () => {
          setIsModalVisible(false);
          //保存用户与公司关联表
          // if (Obj.affiliatedCompanyIds.length > 0) {
          //   debugger;
          //   await saveUserCompany(Obj.id, Obj.affiliatedCompanyIds);
          // }

          handleCancel();
        });
      })
      .catch((info) => { });
  };
  const handleCheckboxChange = (checkedValues) => {
    if (checkedValues.includes('all')) {
      form.setFieldsValue({
        affiliatedCompanyIds: ['all', ...companyList.map((option) => option.value)],
      });
    } else {
      form.setFieldsValue({
        affiliatedCompanyIds: checkedValues,
      });
    }
  };

  const getDetail = (id: any) => {
    request('/sys/account/form', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      data: {
        id,
      },
    }).then(async (res) => {
      let detaildata: any = res?.data;

      //获取用户对应的管理公司
      // await getCheckedCompanyList(id);
      setFieldsValue(detaildata);
      setCheckedCompanyList(detaildata.affiliatedCompanyIds || []);
      setCheckedRoleList(detaildata.roleIds || []);
      setCheckedUserList(detaildata.accessibleUsersIds || []);
      // setFieldsValue({ affiliatedCompanyIds: checkedCompany });
      showModal();
    });
  };
  useImperativeHandle(refs, () => ({
    init: (id: any, record: any) => {
      if (id) {
        setCode(id);
        getDetail(id);
      } else {
        resetFields();
        showModal();
      }

      // setfileList([]);
    },
  }));

  return (
    <>
      <Modal
        title={code === '' ? '新增' : '编辑'}
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
        centered
        width={700}
        maskClosable={false}
        bodyStyle={{
          maxHeight: window.innerHeight - 150,
          overflowY: 'auto',
        }}
      >
        <Form form={form} layout="vertical" {...modalLayoutSm}>
          <Row>
            <Col span={12}>
              <Form.Item
                label="归属公司"
                name="companyId"
                rules={[{ required: true, message: '请选择归属公司' }]}
              >
                <Select>
                  {orglist.map((e: any, i: number) => {
                    return (
                      <Option key={i} value={e.id}>
                        {e.name}
                      </Option>
                    );
                  })}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="归属部门"
                name="deptId"
                rules={[{ required: true, message: '请选择部门' }]}
              >
                {/* <Select>
                  {deptList.map((e: any, i: number) => {
                    return (
                      <Option key={i} value={e.id}>
                        {e.name}
                      </Option>
                    );
                  })}
                </Select> */}
                <TreeSelect
                  showSearch
                  style={{ width: '100%' }}
                  dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                  allowClear
                  treeData={deptList}
                  fieldNames={{
                    label: 'name', value: 'id', children: 'children'
                  }}
                />
              </Form.Item>
            </Col>



            <Col span={12}>
              <Form.Item
                label="登录名"
                name="account"
                rules={[{ required: true, message: '请输入登录名' }]}
              >
                <Input disabled={code !== ''} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="用户名称"
                name="name"
                rules={[{ required: true, message: '请输入用户名称' }]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="用户身份"
                name="userRoleId"
                rules={[{ required: true, message: '请选择用户身份' }]}
              >

                <Select placeholder="请选择">
                  {userRoleTypeListEnum.map((item, i) => {
                    return (
                      <Select.Option key={item.key} title={item.name} value={item.key}>
                        {item.name}
                      </Select.Option>
                    );
                  })}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="用户类型"
                name="userType"
                rules={[{ required: true, message: '请选择用户类型' }]}
              >

                <Select placeholder="请选择">
                  {userTypeListEnum.map((item, i) => {
                    return (
                      <Select.Option key={item.key} title={item.name} value={item.key}>
                        {item.name}
                      </Select.Option>
                    );
                  })}
                </Select>
              </Form.Item>
            </Col>

            <Col span={12}>
              <Form.Item
                label="人员档案"
                name="persionId"

              >

                <Select placeholder="请选择">
                  {personListEnum.map((item, i) => {
                    return (
                      <Select.Option key={item.key} title={item.name} value={item.key}>
                        {item.name}
                      </Select.Option>
                    );
                  })}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="是否允许登录" name="enable">
                <Select>
                  <Option value="1">是</Option>
                  <Option value="0">否</Option>
                </Select>
              </Form.Item>
            </Col>



            <Col span={12}>
              <Form.Item label="手机电话" name="phone">
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="电子邮箱" name="email">
                <Input />
              </Form.Item>
            </Col>

            <Col span={24}>
              <Form.Item label="所管理公司(财务专用)" name="affiliatedCompanyIds">
                <Checkbox indeterminate={indeterminateCompany} onChange={onCheckAllCompanyChange} checked={checkCompanyAll}>
                  全选
                </Checkbox>
                {/* <Divider /> */}
                <CheckboxGroup
                  options={companyList}
                  value={checkedCompanyList}
                  onChange={onCompanyChange}
                />

              </Form.Item>
            </Col>
            <Col span={24}>
              <Form.Item label="所分配角色" name="roleIds">
                <Checkbox indeterminate={indeterminateRole} onChange={onCheckAllRoleChange} checked={checkRoleAll}>
                  全选
                </Checkbox>
                {/* <Divider /> */}
                <CheckboxGroup
                  options={roleList}
                  value={checkedRoleList}
                  onChange={onRoleChange}
                />

              </Form.Item>
            </Col>
            {/* <Col span={24}>
              <Form.Item label="所访问用户" name="accessibleUsersIds">
                <Checkbox indeterminate={false} onChange={onCheckAllUserChange} checked={checkUserAll}>
                  全选
                </Checkbox>
                <CheckboxGroup
                  options={accessibleUsersList}
                  value={checkedUserList}
                  onChange={onUserChange}
                />
                <Checkbox.Group options={accessibleUsersList} />
 
              </Form.Item>
            </Col> */}
          </Row>
        </Form>
      </Modal >
    </>
  );
};
const AddMCom = forwardRef(ProductModal);


export default AddMCom;
